package com.ny.zmb.openapi.exception;

import com.ny.zmb.openapi.controller.entity.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ControllerAdvice;

/**
 * 全局异常处理器
 * czz
 * 20241105
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseEntity<Result> handleMissingParameterException(MissingServletRequestParameterException ex) {
        // 获取缺少的请求参数
        String missingParam = ex.getParameterName();

        // 自定义错误信息
        String errorMessage = "Missing required parameter: " + missingParam;

        // 返回自定义的错误响应
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Result.fail(errorMessage));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Result> handleGeneralException(Exception ex) {
        // 通用异常处理
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Result.fail(ex.getMessage()));
    }
}
